class PostsController < ApplicationController
  before_action :set_post, only: [:edit, :update, :destroy, :show]

  def index
    params[:plate_id] ||= 'news'
    @plate_word = Post.plate_id.options.map(&:reverse).to_h[params[:plate_id]]
    @html_title = "#{@plate_word}管理"
    @posts = Post.with_plate_id(params[:plate_id]).order('order_num asc')
  end

  def new
    @post = Post.new(plate_id: (params[:plate_id] || 'news'))
    @html_title = "新建#{@post.plate_id_text}"
  end

  def show
    render layout: 'home_page'
  end

  def create
    @post = Post.new(post_params)
    respond_to do |format|
      if @post.save
        format.html {redirect_to posts_path(plate_id: @post.plate_id), notice: '创建成功！'}
      else
        format.html {render 'new'}
      end
    end
  end

  def edit
    @html_title = "编辑#{@post.plate_id_text}"
  end

  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html {redirect_to posts_path(plate_id: @post.plate_id), notice: '更新成功！'}
        format.json {render json: 'success'.to_json}
      else
        format.html {render 'edit'}
      end
    end
  end

  def destroy
    @post.destroy
    redirect_to posts_path(plate_id: @post.plate_id), notice: '删除成功！'
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def post_params
    params[:post].permit!
  end
end
